import * as format from './format';

const tools = {
    tryCatch:function(React, ErrorHandler, handlerOptions) {
        if (!React || !React.Component) {
            throw new Error('arguments[0] for react-try-catch-render does not look like React.');
        }
        if (typeof ErrorHandler !== 'function') {
            throw new Error('arguments[1] for react-try-catch-render does not look like a function.');
        }
        /**
         * Implementation of the try/catch wrapper
         * @param  {[React.Component]} component The ES6 React.Component
         */
        return function wrapWithTryCatch(Component) {
            const originalRender = Component.prototype.render;

            Component.prototype.render = function tryRender() {
                try {
                    return originalRender.apply(this, arguments);
                } catch (err) {
                    // Log an error
                    window.console && console.error("errorLog:",err);
                    if(ErrorHandler && ErrorHandler.prototype && ErrorHandler.prototype.render) {
                        return React.createElement(ErrorHandler, handlerOptions);
                    }
                    // ErrorHandler is at least a valid function
                    return ErrorHandler(err);
                }
            };
            return Component;
        };
    },
    formatDate: format.formatToDate,
    formatTime: format.formatToTime,
    getTextWidth(str) {
        let width = 0;
        if (str) {
            for (var i = 0; i < str.length; i++) {
                //如果是汉字
                if (str.charCodeAt(i) > 255) {
                    width += 14;
                }
                else {
                    width += 7;
                }
            }
        }
        return width;
    },
    isWeekendDay(str) {
        let bool = false;
        if (str) {
            let dt = new Date(str);
            if (dt.getDay() == 0 || dt.getDay() == 6) {
                bool = true;
            }
        }
        return bool;
    },
    isBelowIE9() {
      return navigator.appName == "Microsoft Internet Explorer" && parseInt(navigator.appVersion.split(";")[1].replace(/[ ]/g, "").replace("MSIE","")) <= 9;
    },
    camelCase(name) {
      return name.charAt(0).toUpperCase() +
        name.slice(1).replace(/-(\w)/g, (m, n) => {
          return n.toUpperCase();
        });
    }
}
export default tools;